# 了解迭代器和生成器，目的是为了查看for循环原理

x = list(range(10))
y = iter(x)
print(next(y))
print(next(y))


def gen(n):
    for x in range(n):
        yield x ** 2


x = gen(5)
for i in x:
    print(i, end="  ")
print()

# 注意生成器要有小括号
a = (2 * x for x in range(5))
for b in a:
    print(b, end="  ")

# 使用生成器效率更高 占用内存更少
import time
import sys

print()
t1 = time.time()
my_list = [2 * x for x in range(10000000)]
t2 = time.time()
print("使用时间：", t2 - t1)
print("占用内存：", sys.getsizeof(my_list))

t3 = time.time()
# 使用生成器要用小括号
my_gen = (2 * x for x in range(10000000))
t4 = time.time()
print("使用时间：", t4 - t3)
print("占用内存：", sys.getsizeof(my_gen))

# 构造生成绝对值的生成器
test = [-1, -3, -4, 2, 4, 1]
# 生成器（列表表达式）中使用if else
my_gen_test = (t if t > 0 else -t for t in test)
print(list(my_gen_test))
